using System;
using UniRx;
using UnityEngine;

public class JumpComp : MonoBehaviour
{
    private CharacterController _controller;
    private Animator _animator;

    [Header("玩家跳跃速度")] public float jumpSpeed = 6f;
    [Header("玩家落体速度")] public float gravity = 1000f;

    private bool _canJump = true;
    [Header("玩家跳跃冷却事件")] public float jumpCoolDown = 2f;
    private Vector3 _moveDir = Vector3.zero;

    private const string IsJumpingAnimKey = "isJumping";
    private const string VerticalVelocityAnimKey = "verticalVelocity";

    private void Awake()
    {
        _animator = GetComponent<Animator>();
        _controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // 输入移动
        HandleJump();
    }

    private void HandleJump()
    {
        // 跳跃逻辑
        if (Input.GetButton("Jump") && _canJump)
        {
            _animator.SetBool(IsJumpingAnimKey, true); // 触发跳跃动画

            _canJump = false;
            _moveDir.y = jumpSpeed;
            // 利用UniRX 冷却时间到了 设置可以继续跳跃
            Observable.Timer(TimeSpan.FromSeconds(jumpCoolDown))
                .Subscribe(_ => _canJump = true);
            // 移动角色
            _controller.Move(_moveDir * Time.deltaTime);
        }

        // 应用重力
        if (!_controller.isGrounded)
        {
            _moveDir.y -= gravity * Time.deltaTime;
            _animator.SetFloat(VerticalVelocityAnimKey, _moveDir.y); // 下落
            // 移动角色
            _controller.Move(_moveDir * Time.deltaTime);
        }
        else
        {
            _moveDir.y = 0f;
            _animator.SetBool(IsJumpingAnimKey, false); // 停止跳跃动画
        }
    }
}